package com.news.servlet;

import com.news.model.News;
import com.news.service.NewsService;
import com.news.service.impl.NewsServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/newsDetail")
public class NewsDetailServlet extends HttpServlet {
    private NewsService newsService = new NewsServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            
            int newsId = Integer.parseInt(request.getParameter("id"));
            News news = newsService.getNewsById(newsId);
            
            if (news != null) {
                List<News> relatedNews = newsService.getRelatedNews(news.getSort_id(), newsId);
                request.setAttribute("news", news);
                request.setAttribute("relatedNews", relatedNews);
//                request.setAttribute("message", "新闻加载成功");
                request.getRequestDispatcher("newsDetail.jsp").forward(request, response);
            } else {
                request.setAttribute("message", "新闻不存在");
                response.sendRedirect("index");
            }
        } catch (NumberFormatException e) {
            request.setAttribute("message", "无效的新闻ID");
            response.sendRedirect("index");
        } catch (Exception e) {
            request.setAttribute("message", "系统错误：" + e.getMessage());
            response.sendRedirect("index");
        }
    }
} 